package com.twetec.cms.adapter.pc.backend.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Elastic Search 配置类
 */
@Configuration
public class ElasticSearchConfig {

    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);

    @Value("${elastic-search.host-name}")
    private String hostName;

    @Value("${elastic-search.port}")
    private Integer port;

    @Bean
    public ElasticsearchClient searchClient() {
        // 创建客户端构造器
        RestClientBuilder restClientBuilder = RestClient.builder(
                new HttpHost(hostName, port)
        );

        // 设定http客户端连接
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder builder) {
                builder.setDefaultIOReactorConfig(
                        IOReactorConfig.custom().setIoThreadCount(2).build()
                );

                return builder;
            }
        });

        // 设定请求
        restClientBuilder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
                // 设定请求超时时间(单位：ms)
                builder.setConnectTimeout(5000).setSocketTimeout(60000);

                return builder;
            }
        });

        // 设定异常监听器
        restClientBuilder.setFailureListener(new RestClient.FailureListener(){
            @Override
            public void onFailure(Node node) {
                logger.info("elastic search 全局异常监听器报错咯...");
            }
        });

        RestClient restClient = restClientBuilder.build();

        ElasticsearchTransport elasticsearchTransport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // 异步的 elastic search 客户端
//        ElasticsearchAsyncClient elasticsearchAsyncClient = new ElasticsearchAsyncClient(elasticsearchTransport);

        ElasticsearchClient elasticsearchClient = new ElasticsearchClient(elasticsearchTransport);

        return elasticsearchClient;
    }
}
